package com.csust.cg.mongodb.contorller;

import com.csust.cg.mongodb.domain.HttpStatus;
import com.csust.cg.mongodb.domain.Result;
import com.csust.cg.mongodb.service.CollectionsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author chenguang
 */
@RequestMapping("/api")
@RestController
@ResponseBody
public class CollectionsController {

    @Autowired
    private CollectionsService collectionsService;

    @GetMapping("/getCollectionsInfoList")
    public Result getCollectionsInfoList(@RequestParam String connectionId, @RequestParam String databaseName) {
        if (StringUtils.isBlank(connectionId)) {
            new Result("连接ID不能为空！", HttpStatus.CONNECT_ID_IS_NULL);
        }
        if (StringUtils.isBlank(databaseName)) {
            new Result("数据库名不能为空！", HttpStatus.BAD_REQUEST);
        }
        return collectionsService.getCollectionsInfoList(connectionId, databaseName);
    }

    @PostMapping("/createCollection")
    public Result createCollection(@RequestParam String connectionId, @RequestParam String databaseName, @RequestParam String collectionName) {
        if (StringUtils.isBlank(connectionId)) {
            new Result("连接ID不能为空！", HttpStatus.CONNECT_ID_IS_NULL);
        }
        if (StringUtils.isBlank(databaseName)) {
            new Result("数据库名不能为空！", HttpStatus.BAD_REQUEST);
        }
        if (StringUtils.isBlank(collectionName)) {
            new Result("集合名不能为空！", HttpStatus.BAD_REQUEST);
        }
        return collectionsService.createCollection(connectionId, databaseName, collectionName);
    }

    @PostMapping("/dropCollection")
    public Result dropCollection(@RequestParam String connectionId, @RequestParam String databaseName, @RequestParam String collectionName) {
        if (StringUtils.isBlank(connectionId)) {
            new Result("连接ID不能为空！", HttpStatus.CONNECT_ID_IS_NULL);
        }
        if (StringUtils.isBlank(databaseName)) {
            new Result("数据库名不能为空！", HttpStatus.BAD_REQUEST);
        }
        if (StringUtils.isBlank(collectionName)) {
            new Result("集合名不能为空！", HttpStatus.BAD_REQUEST);
        }
        return collectionsService.dropCollection(connectionId, databaseName, collectionName);
    }
}
